package com.example.movie.controller;

import com.example.movie.model.Movie;
import com.example.movie.repository.MovieRepository;
import com.example.movie.service.MovieService;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.Id;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("movie")
public class MovieController {
	@Resource
	MovieService movieService;
	@Resource
	MovieRepository movieRepository;
	
	@GetMapping("list")
	public List<Movie> list() {
		return movieService.listMovie();
	}
	
	@PutMapping
	public Integer save(@RequestBody Movie movie) {
		return movieService.saveMovie(movie);
	}
	
	@DeleteMapping
	public Integer remove(Integer id) {
		return movieService.removeMovie(id);
	}
	
	@DeleteMapping("all")
	public void removeAll() {
		movieRepository.deleteAll();
	}
	
	@PutMapping("batch")
	public List<Integer> saveBatch(@RequestBody List<MovieVo> movies) {
		List<Movie> list = movies.stream().map(MovieVo::convert).collect(Collectors.toList());
		movieRepository.saveAll(list);
		return list.stream().map(Movie::getId).collect(Collectors.toList());
	}
	
	
	@Data
	public static class MovieVo {
		private Integer movieId;
		private String movieName;
		private String releaseInfo;
		
		public Movie convert() {
			Movie movie = new Movie();
			movie.setId(this.getMovieId());
			movie.setName(this.getMovieName());
			movie.setReleaseInfo(this.getReleaseInfo());
			return movie;
		}
	}
	
	
}
